package com.jiang.jetpackdemo.viewModel

import android.app.AlertDialog
import android.app.Application
import android.content.DialogInterface
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.gson.Gson
import com.jiang.jetpackdemo.database.RoomHelper
import com.jiang.jetpackdemo.fragment.VideoRecommendFragment
import com.jiang.jetpackdemo.http.RetrofitManager
import com.jiang.jetpackdemo.model.FavoritesModel
import com.jiang.jetpackdemo.model.ImgInfo
import com.jiang.jetpackdemo.model.VideoRecommendInfo
import com.jiang.jetpackdemo.utils.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.time.ZonedDateTime

/**
 *
 * @ProjectName:    JetpackDemo
 * @ClassName:      PlayVideoViewModel
 * @Description:     java类作用描述
 * @Author:         江
 * @CreateDate:     2020/4/2 14:46
 */
class PlayVideoViewModel(application: Application) : AndroidViewModel(application) {
    val playResultBean: MutableLiveData<VideoRecommendInfo.ResultBean> by lazy { MutableLiveData<VideoRecommendInfo.ResultBean>() }
    val videoInfoList: MutableLiveData<MutableList<VideoRecommendInfo.ResultBean>> by lazy { MutableLiveData<MutableList<VideoRecommendInfo.ResultBean>>() }
    val sizeOfVideoInfoList: MutableLiveData<Int> by lazy { MutableLiveData<Int>() }
    private val roomHelper: RoomHelper by lazy { RoomHelper(application.applicationContext) }

    init {
        playResultBean.value =
            VideoRecommendInfo.ResultBean()
        videoInfoList.value = ArrayList()
        sizeOfVideoInfoList.value = 0
    }

    fun getDataFromNet(id: Int, onError: () -> Unit, onFinish: () -> Unit) {
        viewModelScope.launch(Dispatchers.IO) {
            val videoRecommendInfo = RetrofitManager.getVideoRecommendInfo(id)
            val result = videoRecommendInfo?.result
            if (result.isNullOrEmpty()) {
                withContext(Dispatchers.Main) {
                    onError()
                }
            } else {
                result.removeAt(0)
                videoInfoList.value?.apply {
                    clear()
                    addAllAndChange(result, sizeOfVideoInfoList)
                }
                withContext(Dispatchers.Main) {
                    onFinish()
                }
            }
        }
    }

    fun getDataFromIntent(stringExtra: String) {
        if (stringExtra.isNullOrEmpty()) {
            //finish()
            Toast.makeText(getApplication(), "解析失败 :$stringExtra", Toast.LENGTH_LONG).show()
        } else {
            playResultBean.value =
                Gson().fromJson(stringExtra, VideoRecommendInfo.ResultBean::class.java)
        }
    }

    fun addInFavorites(resultBean: VideoRecommendInfo.ResultBean) {
        viewModelScope.launch(Dispatchers.Main) {
            val favoritesModel =
                FavoritesModel(
                    null,
                    resultBean.data.title,
                    FavoritesModel.TYPE_VIDEO,
                    resultBean.data.playUrl,
                    resultBean.data.description,
                    resultBean.data.cover.feed,
                    timeFormatter.format(ZonedDateTime.now()),
                    recommendId = resultBean.data.id
                )
            if (isAlreadyCollected(favoritesModel, roomHelper.favoritesModelDao)) {
                Toast.makeText(getApplication(), "已经收藏过了", Toast.LENGTH_SHORT).show()
            } else {
                withContext(Dispatchers.IO) {
                    roomHelper.favoritesModelDao.insert(favoritesModel)
                }
                Toast.makeText(getApplication(), "收藏成功", Toast.LENGTH_SHORT).show()
            }
        }
    }

    fun downloadVideo() {
        val playUrl = playResultBean.value?.data?.playUrl!!
        val fileName = "${fixString(playUrl)}.mp4"
        Log.d("downloadVideo", "$fileName")
        if (hasSameFile(getApplication(), playUrl, true)) {
            Toast.makeText(getApplication(), "已经下载过了", Toast.LENGTH_SHORT).show()
        } else {
          //  downloadFile(getApplication(), playUrl, fileName)
            Toast.makeText(getApplication(), "开始下载了", Toast.LENGTH_SHORT).show()
        }

    }


}